package cn.kimming.rpc.remoting.strategy;

import cn.kimming.rpc.remoting.registry.InstanceDetail;
import org.apache.curator.x.discovery.ProviderStrategy;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.details.InstanceProvider;

import java.util.List;

/**
 * 最少调用次数策略
 */
public class LeastCallStrategy implements ProviderStrategy<InstanceDetail> {
    @Override
    public ServiceInstance<InstanceDetail> getInstance(InstanceProvider<InstanceDetail> instanceProvider) throws Exception {
        List<ServiceInstance<InstanceDetail>> instances = instanceProvider.getInstances();
        if (instances.size() == 0 )
        {
            return null;
        }
        int minIndex = 0;
        int minCallCount = instances.get(0).getPayload().getCallCount();
        for (int i = 1; i < instances.size(); i++) {
            int callCount = instances.get(i).getPayload().getCallCount();
            if (callCount < minCallCount) {
                minCallCount = callCount;
                minIndex = i;
            }
        }
        return instances.get(minIndex);
    }
}
